package blue.http.internal.core.net;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerKeepAliveHandler;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author Jin Zheng
 * @since 1.0 2021-08-16
 */
public class HttpInitializer extends ChannelInitializer<SocketChannel> {
	private final DefaultHttpServerBuilder builder;

	public HttpInitializer(DefaultHttpServerBuilder builder) {
		this.builder = builder;
	}

	@Override
	protected void initChannel(SocketChannel sc) throws Exception {
		ChannelPipeline cp = sc.pipeline();
		if (builder.getSslOptions() != null) {
			cp.addLast(builder.getSslOptions().getSslContext().newHandler(sc.alloc()));
		}

		cp.addLast(new HttpServerCodec());
		cp.addLast(new HttpServerKeepAliveHandler());

		if (builder.getHttpOptions() != null) {
			cp.addLast(new ChunkedWriteHandler());
			cp.addLast(new HttpServerHandler(builder));
		}

		if (builder.getWebSocketOptions() != null) {
			String wsRoot = builder.getWebSocketOptions().getRoot();
			cp.addLast(new HttpObjectAggregator(Short.MAX_VALUE * 10));
			cp.addLast(new WebSocketServerProtocolHandler(wsRoot, null, true));
			cp.addLast(new WebSocketServerHandler(builder));
		}
	}

}
